package org.example.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;


public class SqlSessionUtil {
    private static final SqlSessionFactory SQL_SESSION_FACTORY;

    static {
        //配置文件
        String config = "mybatis.xml";
        //将配置文件转化为流对象
        InputStream in = null;

        //创建SqlSessionFactory的构建对象
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = null;

        try {
            //将配置文件转化为流对象
            in = Resources.getResourceAsStream(config);
            //创建SqlSessionFactory的构建对象
            sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //通过配置信息 构建 SqlSessionFactory工厂
        SQL_SESSION_FACTORY = sqlSessionFactoryBuilder.build(in);
    }


    public static SqlSession getSession() {
        return SQL_SESSION_FACTORY.openSession();
    }
}
